﻿using System.IO;
using System.Text;

namespace Smart.Model
{
    public static class StreamHelper
    {
        static byte[] ms_encode_buffer = new byte[1024];
        public static void Encode(this Stream stream, int value)
        {
            byte[] buffer = new byte[4];
            buffer[0] = (byte)(value & 0xFF);
            buffer[1] = (byte)((value >> 8) & 0xFF);
            buffer[2] = (byte)((value >> 16) & 0xFF);
            buffer[3] = (byte)(value >> 24);
            stream.Write(buffer, 0, buffer.Length);
        }

        public static void Encode(this Stream stream, long value)
        {
            byte[] buffer = new byte[8];
            buffer[0] = (byte)(value & 0xFF);
            buffer[1] = (byte)((value >> 8) & 0xFF);
            buffer[2] = (byte)((value >> 16) & 0xFF);
            buffer[3] = (byte)((value >> 24) & 0xFF);
            buffer[4] = (byte)((value >> 32) & 0xFF);
            buffer[5] = (byte)((value >> 40) & 0xFF);
            buffer[6] = (byte)((value >> 48) & 0xFF);
            buffer[7] = (byte)((value >> 56) & 0xFF);
            stream.Write(buffer, 0, buffer.Length);
        }

        public static void Encode(this Stream stream, uint value)
        {
            byte[] buffer = new byte[4];
            buffer[0] = (byte)(value & 0xFF);
            buffer[1] = (byte)((value >> 8) & 0xFF);
            buffer[2] = (byte)((value >> 16) & 0xFF);
            buffer[3] = (byte)(value >> 24);
            stream.Write(buffer, 0, buffer.Length);
        }

        public static void Encode(this Stream stream, string value)
        {
            //写入长度
            if (string.IsNullOrEmpty(value))
                value = string.Empty;
            byte[] writeBytes = Encoding.UTF8.GetBytes(value);
            stream.Encode(writeBytes.Length);
            stream.Write(writeBytes, 0, writeBytes.Length);
        }

        public static int ReadInt(this byte[] contents, ref int pos)
        {
            int v = contents[pos] | (contents[pos + 1] << 8) | (contents[pos + 2] << 16) | (contents[pos + 3] << 24);
            pos += 4;
            return v;
        }

        public static long ReadLong(this byte[] contents, ref int pos)
        {
            int key = ReadInt(contents, ref pos);
            long value = ReadInt(contents, ref pos);
            long val = ((value & 0xFFFFFFFF) << 32) | ((long)key);
            return val;
        }

        public static string ReadString(this byte[] contents, ref int pos)
        {
            int length = contents[pos] | (contents[pos + 1] << 8) | (contents[pos + 2] << 16) | (contents[pos + 3] << 24);
            pos += 4;
            string v = System.Text.Encoding.UTF8.GetString(contents, pos, length);
            pos += length;
            return v;
        }
    }
}